<template>
  <div class="app-container">
    <el-card class="table-card">
      <div slot="header" class="clearfix">
        <toolbar :config="toolbarConfig" :search="toolbarSearch" @dialog="showDialog" />
      </div>
      <div class="table-container">
        <el-table v-el-height-adaptive-table="{bottomOffset: 88}" v-loading="tableLoading" :data="tableData" border size="small" width="100%" height="100px">
          <el-table-column type="selection" align="center" width="55"></el-table-column>
          <el-table-column prop="username" align="center" label="用户名" width="180"></el-table-column>
          <el-table-column prop="nickname" align="center" label="昵称" width="180"></el-table-column>
          <el-table-column prop="email" align="center" label="邮箱" width="180"></el-table-column>
          <el-table-column prop="telephone" align="center" label="电话"></el-table-column>
          <el-table-column prop="updated_at" align="center" label="更新时间"></el-table-column>
          <el-table-column prop="status" align="center" label="状态">
            <template slot-scope="{row}">
              <el-tag :type="row.status | statusTagFilter" size="mini">
                {{ row.status | statusTextFilter }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column align="center" label="操作" width="400">
            <template slot-scope="{row}">
              <el-button type="text" size="mini" @click="edit(row)">
                编辑
              </el-button>
              <el-button v-if="row.status!=='deleted'" size="mini" type="text" @click="del(row)">
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <pagination
        :current-page="currentPage"
        :page-size="pageSize"
        :total="total">
      </pagination>
    </el-card>
    <el-dialog
      :title="dialogTitle"
      width="30%"
      :visible.sync="dialogVisible">
      <el-form ref="form" :model="form" :rules="rules" :validate-on-rule-change="false" auto-complete="off" label-width="90px" size="small">
        <el-form-item prop="roles" label="所属角色">
          <el-select v-model="form.roles" multiple placeholder="请选择" style="width: 100%">
            <el-option
              v-for="item in rolesData"
              :key="item.id"
              :label="item.display_name"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="username" label="用户名">
          <el-input v-model="form.username"></el-input>
        </el-form-item>
        <el-form-item prop="nickname" label="昵称">
          <el-input v-model="form.nickname"></el-input>
        </el-form-item>
        <el-form-item prop="email" label="邮箱">
          <el-input v-model="form.email"></el-input>
        </el-form-item>
        <el-form-item prop="telephone" label="手机号">
          <el-input v-model="form.telephone"></el-input>
        </el-form-item>
        <el-form-item prop="password" label="密码">
          <el-input v-model="form.password" type="password" placeholder="不更改密码可以忽略"></el-input>
        </el-form-item>
        <el-form-item prop="password_confirmation" label="确认密码">
          <el-input v-model="form.password_confirmation" type="password"></el-input>
        </el-form-item>
        <el-form-item prop="status" label="状态">
          <el-radio-group v-model="form.status" size="mini">
            <el-radio :label="1">正常</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button size="small" @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" size="small" @click="save">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import Toolbar from '@/components/Toolbar'
import Pagination from '@/components/Pagination'
import { Message } from 'element-ui'
import { getUserList, getRoleList, createUser, updateUser, destroyUser } from '@/api/system/user'
import elHeightAdaptiveTable from '@/directive/el-table'
import {
  validatePassword,
  validateRePassword,
  validateUpdatePassword,
  validateUpdateRePassword,
  validateUsername
} from '@/utils/validate'
import { deepClone } from '@/utils'

export default {
  components: {
    Toolbar,
    Pagination
  },
  directives: { elHeightAdaptiveTable },
  data() {
    return {
      toolbarConfig: [],
      toolbarSearch: {
        enable: true,
        placeholder: '请输入搜索值'
      },
      tableLoading: true,
      tableData: [],
      tableHeight: '120px',
      rolesData: [],
      dialogVisible: false,
      currentPage: 1,
      pageSize: 10,
      total: 0,
      dialogTitle: '',
      form: {
        id: 0,
        roles: [],
        username: '',
        nickname: '',
        email: '',
        telephone: '',
        password: '',
        password_confirmation: '',
        status: 1,
        updated_at: ''
      },
      rules: {
        roles: [
          { type: 'array', required: true, message: '请至少选择一个角色', min: 1, trigger: 'blur' }
        ],
        username: [
          { type: 'string', required: true, trigger: 'blur', validator: validateUsername }
        ],
        nickname: [
          { type: 'string', required: true, message: '请输入昵称', trigger: 'blur' }
        ],
        email: [
          { type: 'email', required: true, message: '请输入有效的邮箱', trigger: 'blur' }
        ],
        telephone: [
          { required: true, message: '请输入手机号', trigger: ['blur', 'change'] },
          { pattern: /^1(2|3|4|5|6|7|8|9)[0-9]{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
        ],
        status: [
          { type: 'enum', required: true, message: '请选择状态', trigger: 'blur', enum: [0, 1] }
        ]
      },
      createRules: {
        password: [
          { type: 'string', required: true, message: '请输入密码', trigger: 'blur', validator: validatePassword }
        ],
        password_confirmation: [
          { required: true, trigger: ['blur', 'change'], validator: validateRePassword }
        ]
      },
      updateRules: {
        password: [
          { type: 'string', trigger: 'blur', validator: validateUpdatePassword }
        ],
        password_confirmation: [
          { type: 'string', trigger: 'blur', validator: validateUpdateRePassword }
        ]
      }
    }
  },
  watch: {
    dialogVisible(newVal) {
      if (newVal === true && this.rolesData.length === 0) {
        this.getRoleList()
      }
    },
    'form.id': {
      handler(newVal) {
        this.$nextTick(() => {
          if (newVal) {
            this.rules = {
              ...this.rules,
              ...this.updateRules
            }
          } else {
            this.rules = {
              ...this.rules,
              ...this.createRules
            }
          }
        })
      },
      immediate: true
    }
  },
  created() {
    this.getList()
  },
  methods: {
    getList() {
      getUserList().then(response => {
        const { code, data, message } = response
        if (code === 1) {
          this.tableData = data.list
          this.currentPage = data.meta.current_page
          this.pageSize = data.meta.per_page
          this.total = data.meta.total
          this.toolbarConfig = data.permissions || []
        } else {
          Message({
            message: message || 'Error',
            type: 'error'
          })
        }
        this.tableLoading = false
      }).catch(() => {
        this.tableLoading = false
      })
    },
    getRoleList() {
      getRoleList().then(response => {
        const { code, data, message } = response
        if (code === 1) {
          this.rolesData = data
        } else {
          Message({
            message: message || 'Error',
            type: 'error'
          })
        }
      })
    },
    showDialog(event, text, type) {
      if (event === 'add') {
        this.add(text)
      } else if (event === 'del') {
        this.del()
      }
    },
    add() {
      this.dialogTitle = '添加用户'
      if (this.$refs['form'] !== undefined) {
        this.$refs.form.resetFields()
      }
      if (this.form.id > 0) {
        this.form = {
          ...this.form,
          ...{
            id: 0,
            password: '',
            password_confirmation: '',
            updated_at: ''
          }
        }
      }
      this.dialogVisible = true
    },
    edit(row) {
      this.dialogTitle = '编辑用户'
      if (this.$refs['form'] !== undefined) {
        this.$refs.form.resetFields()
      }
      this.form = deepClone(row)
      this.dialogVisible = true
    },
    save() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          if (!this.form.id) {
            createUser(this.form).then(response => {
              const { code, data, message } = response
              if (code === 1) {
                this.tableData.unshift(data)
              } else {
                Message({
                  message: message || 'Error',
                  type: 'error'
                })
              }
            })
          } else {
            updateUser(this.form).then(response => {
              const { code, data, message } = response
              if (code === 1) {
                const index = this.tableData.findIndex(item => {
                  return item.id === data.id
                })
                this.tableData.splice(index, 1, data)
              } else {
                Message({
                  message: message || 'Error',
                  type: 'error'
                })
              }
            })
          }
          this.dialogVisible = false
        } else {
          return false
        }
      })
    },
    del(row) {
      destroyUser(row).then(response => {
        const { code, message } = response
        if (code === 1) {
          const index = this.tableData.findIndex(item => {
            return item.id === row.id
          })
          this.tableData.splice(index, 1)
        } else {
          Message({
            message: message || 'Error',
            type: 'error'
          })
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
</style>
